<template>
	<view class="app-container">
		<button class="item" type="primary">涂鸦登录({{isLogin?'已登录':'未登录'}})</button>
		<button class="item" type="primary" @click="onItemClick(0)">插件页面直接进行蓝牙配网</button>
		<button class="item" type="primary" @click="onItemClick(1)">设备列表</button>
	</view>
</template>

<script>
	import {
		isLogin,
		loginByWx,
		getFamilies,
		changeFamily,
		getCurrentFamily,
		openDistribution,
	} from '@ray-js/wechat';
	import {
		judgeMyApi
	} from '@/utils/tuya.js'
	export default {
		data() {
			return {
				isLogin: false,
			}
		},
		onLoad() {
			this.initLogin()
		},
		methods: {

			//初始化登录
			async initLogin() {
				const hasLogin = await isLogin();
				this.isLogin = hasLogin
				if (!hasLogin) {
					this.wxLogin()
					return
				};
				try {
					const homes = await getFamilies();
					changeFamily(homes[0]);
				} catch (e) {
					this.isLogin = false
				}
			},
			//微信登录
			async wxLogin() {
				let canIuse = await judgeMyApi({
					myApi: 'getUserProfile',
					myVersion: '2.24.0',
				});
				if (!canIuse) return false;
				uni.showLoading({
					title: '正在登陆'
				})
				try {
					await loginByWx();
					uni.showToast({
						title: '登录成功',
						duration: 1000,
					});
					this.isLogin = true
					// 获取家庭
					const homes = await getFamilies();
					changeFamily(homes[0]);
				} catch (e) {
					uni.showToast({
						title: '登录失败',
						icon: 'error',
						duration: 1000,
					});
				} finally {
					wx.hideLoading();
				}
			},
			//插件页面直接进行蓝牙配网
			async _distributionNetwork() {
				const homeInfo = await getCurrentFamily();
				const {
					homeId
				} = homeInfo
				openDistribution({
					homeId: homeId,
					themeColor: 'blue', // 主题色
				});
			},
			async onItemClick(index) {
				// 判断手机蓝牙是否打开
				const result = await uni.openBluetoothAdapter().catch(err => {
					if (err.errCode) {
						uni.showToast({
							icon: 'none',
							title: '请打开手机蓝牙后进行操作'
						})
					} else {
						uni.showModal({
							title: '提示',
							content: err.errMsg
						})
					}
				})
				if (result) {
					uni.closeBluetoothAdapter()
					switch (index) {
						case 0: //插件页面直接进行蓝牙配网
							this._distributionNetwork()
							break;
						case 1: //设备列表
							uni.navigateTo({
								url: '/pages/devicelist/index'
							})
							break
						default:
							break;
					}
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.app-container {
		.item {
			margin: 20upx 20upx 0;
		}
	}
</style>